package edu.pw.p2pclient.data;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import edu.pw.p2pclient.R;
import edu.pw.p2pclient.logic.SharedManager;
import edu.pw.p2pclient.utils.FilenameComparator;
import edu.pw.p2pclient.utils.NodeComparator;

public class DirectoryTreeAdapter extends ArrayAdapter<Node> {

	private String mCurrentFolder;
	private ListView mListView;
	private boolean mFiles;
	private int mSelectedCounter;
	private ViewHolder mViewHolder;

	public DirectoryTreeAdapter(Context context, ListView listView,
			boolean files) {

		super(context, R.layout.add_to_shared_row);
		mCurrentFolder = "";
		mListView = listView;
		mFiles = files;
		mSelectedCounter = 0;
	}

	public void deselectItems() {

		for (int i = 0; i < getCount(); ++i)
			getItem(i).setSelected(false);
	}

	public ArrayList<Node> getSelectedItems() {

		ArrayList<Node> result = new ArrayList<Node>();
		for (int i = 0; i < getCount() && mSelectedCounter > result.size(); ++i) {
			if (getItem(i).isSelected())
				result.add(getItem(i));
		}
		return result.size() > 0 ? result : null;
	}

	public void setCurrentFolder(String path) {

		mSelectedCounter = 0;
		mCurrentFolder = path;
	}

	public String getCurrentFolder() {

		return mCurrentFolder;
	}

	public String getParentFolder() {

		return mCurrentFolder.substring(0,
				Math.max(mCurrentFolder.lastIndexOf("/"), 1));
	}

	public boolean isAnySelected() {

		return mSelectedCounter != 0;
	}

	public void refreshAdapter() {

		showDirectory(mCurrentFolder);
	}

	public void showDirectory(String newPath) {

		setCurrentFolder(newPath);
		clear();
		if (mFiles) {
			File newRoot = new File(mCurrentFolder);
			if (!newRoot.getAbsolutePath().equals(TreeNode.ROOT_PATH))
				add(new Node(newRoot.getAbsolutePath(), Node.MOVE_UP));
			File array[] = newRoot.listFiles();
			if (array != null && array.length > 0) {
				ArrayList<File> files = new ArrayList<File>(
						Arrays.asList(array));
				Collections.sort(files, new FilenameComparator());
				HashMap<String, Node> shared = SharedManager.getInstance()
						.getSharedFrom(mCurrentFolder);
				for (File file : files) {
					Node n = shared.get(file.getName());
					add(new Node(file, (n == null ? null : n.getSharingInfo())));
				}
			}
		} else {
			if (!getCurrentFolder().equals(TreeNode.ROOT_PATH))
				add(new Node(getParentFolder(), Node.MOVE_UP));
			ArrayList<Node> nodes = new ArrayList<Node>(SharedManager
					.getInstance().getSharedFrom(newPath).values());
			Collections.sort(nodes, new NodeComparator());
			for (Node node : nodes)
				add(node);
		}
		notifyDataSetChanged();
		mListView.setSelectionAfterHeaderView();
	}

	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {

		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.add_to_shared_row, parent,
					false);

			mViewHolder = new ViewHolder();

			mViewHolder.checkBox = (CheckBox) convertView
					.findViewById(R.id.rowCheckBox);
			mViewHolder.name = (TextView) convertView
					.findViewById(R.id.rowFilenameTextView);
			mViewHolder.image = (ImageView) convertView
					.findViewById(R.id.rowImageView);
			mViewHolder.size = (TextView) convertView
					.findViewById(R.id.rowSizeTextView);

			convertView.setTag(mViewHolder);
		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}

		final Node node = getItem(position);

		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (!node.isFile())
					showDirectory((node.isMoveUp() ? getParentFolder() : node
							.getFullPath()));

			}
		});
		convertView.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				((Activity) getContext()).openContextMenu(v);
				return true;
			}
		});

		if (mFiles) {
			mViewHolder.checkBox.setVisibility(node.isMoveUp() ? View.INVISIBLE
					: View.VISIBLE);
			mViewHolder.checkBox.setChecked(node.isSelected());
			mViewHolder.checkBox.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					boolean isSelected = ((CheckBox) v).isChecked();
					updateCounter(isSelected);
					node.setSelected(isSelected);
				}
			});
		} else
			mViewHolder.checkBox.setVisibility(View.GONE);

		mViewHolder.name.setText(node.getName());

		if (node.isMoveUp())
			mViewHolder.image.setImageResource(R.drawable.move_waiting_up);
		else if (node.isFile()) {
			int res = 0;
			if (node.isShared() && node.isPush())
				res = R.drawable.file_shared_push;
			else if (node.isShared())
				res = R.drawable.file_shared;
			else if (node.isPush())
				res = R.drawable.file_push;
			else
				res = R.drawable.file;
			mViewHolder.image.setImageResource(res);
			mViewHolder.size.setVisibility(View.VISIBLE);
		} else {
			int res = 0;
			if (node.isShared() && node.isPush())
				res = R.drawable.folder_shared_push;
			else if (node.isShared())
				res = R.drawable.folder_shared;
			else if (node.isPush())
				res = R.drawable.folder_push;
			else
				res = R.drawable.folder;
			mViewHolder.image.setImageResource(res);
			mViewHolder.size.setVisibility(View.INVISIBLE);
		}
		mViewHolder.size.setText(node.getSize());

		return convertView;
	}

	protected void updateCounter(boolean checked) {

		if (checked)
			++mSelectedCounter;
		else
			--mSelectedCounter;
	}

	private class ViewHolder {
		CheckBox checkBox;
		TextView name;
		ImageView image;
		TextView size;
	}
}